package com.newcoretech.platform_service

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.widget.Toast
import com.newcoretech.platform_service.image_picker.NDImagePicker
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry


/** PlatformServicePlugin */
class PlatformServicePlugin : FlutterPlugin, MethodCallHandler, ActivityAware,
    PluginRegistry.ActivityResultListener,
    PluginRegistry.RequestPermissionsResultListener {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    private var imagePicker: NDImagePicker = NDImagePicker()
    private var pendingResult: Result? = null
    private lateinit var activity: Activity
    private lateinit var scannerPlugin: NDScannerPlugin

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        scannerPlugin = NDScannerPlugin()
        scannerPlugin.onAttachedToEngine(flutterPluginBinding, this);
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "platform_service")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        pendingResult = result
        if (call.method == "getPlatformVersion") {
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else if (call.method == "pickImages") {
            val arguments = call.arguments as? Map<*, *>?

            imagePicker.initParams(arguments)
            //选取相册
            if (imagePicker.checkPermission(
                    imagePicker.permissionsPickImage,
                    activity
                )
            ) {
                imagePicker.startGallery(activity)
            }
        } else if (call.method == "takePicture") {
            if (imagePicker.checkPermission(
                    imagePicker.permissionsTakePhoto,
                    activity
                )
            ) {
                //拍照
                imagePicker.takePicture(activity)
            }
        } else if (call.method == "PDAEnable" || call.method == "PDADisable" || call.method == "ScanImage") {
            if (call.method == "ScanImage") {
                if (scannerPlugin.checkPermission(
                        scannerPlugin.requestCamera,
                        activity
                    )
                ) {
                    scannerPlugin.onMethodCall(call, result)
                }
            } else {
                scannerPlugin.onMethodCall(call, result)
            }

        } else {
            result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        scannerPlugin.onDetachedFromEngine(binding)
        channel.setMethodCallHandler(null)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == imagePicker.requestPick || requestCode == imagePicker.requestTakePhoto) {
                imagePicker.onActivityResult(requestCode, resultCode, data, activity, pendingResult)
                pendingResult = null
                return true
            }
            if (requestCode == scannerPlugin.requestCamera) {
                pendingResult = null
                return true
            }
        }
//        pendingResult?.error("未选择图片", null, null)
//        pendingResult = null
        return false
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ): Boolean {
        if ((requestCode == imagePicker.permissionsTakePhoto || requestCode == imagePicker.permissionsPickImage)) {
            imagePicker.onRequestPermissionsResult(requestCode, grantResults, activity)
            return true
        } else {
            var allAllow = true
            var permission = ""
            for (res in grantResults) {
                var i = grantResults.indexOf(res);
                if (res != PackageManager.PERMISSION_GRANTED) {
                    allAllow = false
                    if (permissions[i] == Manifest.permission.CAMERA) {
                        permission = "相机"
                    } else if (permissions[i] == Manifest.permission.WRITE_EXTERNAL_STORAGE) {
                        permission = "存储"
                    } else if (permissions[i] == Manifest.permission.READ_EXTERNAL_STORAGE) {
                        permission = "存储"
                    } else if (permissions[i] == Manifest.permission.MANAGE_MEDIA) {
                        permission = "文件管理"
                    } else if (permissions[i] == Manifest.permission.READ_PHONE_STATE) {
                        permission = "手机状态"
                    }
                    break
                }
            }
            if (allAllow) {
                return true
            } else {
                val dialog = android.app.AlertDialog.Builder(activity)
                    .setTitle("提示")
                    .setCancelable(false)
                    .setMessage("App需要" + permission + "权限，请前往设置里授予该权限")
                    .setNegativeButton("前往开启") { dialog, which -> //跳转应用消息，间接打开应用权限设置-效率高
                        val intent = Intent()
                        intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                        val uri =
                            Uri.fromParts(
                                "package",
                                activity.packageName,
                                null
                            )
                        intent.data = uri
                        activity.startActivity(intent)
                    }.setPositiveButton("取消") { dialog, which -> //跳转应用消息，间接打开应用权限设置-效率高
                        Toast.makeText(activity, permission + "权限未开启", Toast.LENGTH_SHORT).show()
                        dialog.dismiss()
                    }
                dialog.show()
            }
        }
        return false
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
        binding.addActivityResultListener(this)
        binding.addRequestPermissionsResultListener(this)
        scannerPlugin.onAttachedToActivity(binding)
    }

    override fun onDetachedFromActivityForConfigChanges() {
        scannerPlugin.onDetachedFromActivityForConfigChanges()
    }

    override fun onReattachedToActivityForConfigChanges(activityBinding: ActivityPluginBinding) {
        scannerPlugin.onReattachedToActivityForConfigChanges(activityBinding)
    }

    override fun onDetachedFromActivity() {
        scannerPlugin.onDetachedFromActivity()
    }
}
